<template>
  <view class="coach-list-container">
    <view class="header-section">
      <text class="page-title">教练管理</text>
    </view>
    
    <view class="toolbar-section">
      <button class="action-button" @click="showCreateCoachModal">添加教练</button>
    </view>
    
    <view class="coach-list">
      <view class="coach-item" v-for="coach in coachList" :key="coach.id" @click="goToDetail(coach.id)">
        <view class="coach-info">
          <text class="coach-name">{{ coach.name }}</text>
          <text class="coach-specialty">{{ coach.specialty }}</text>
          <text class="coach-contact">{{ coach.phone }} | {{ coach.email }}</text>
          <text class="coach-experience">{{ coach.experience }}年经验</text>
        </view>
        <view class="coach-status">
          <text class="status-tag" :class="coach.status === 1 ? 'status-active' : 'status-inactive'">
            {{ coach.status === 1 ? '在职' : '离职' }}
          </text>
        </view>
        <view class="coach-actions">
          <button class="action-button small" @click.stop="editCoach(coach)">编辑</button>
          <button class="action-button small danger" @click.stop="deleteCoach(coach)">删除</button>
        </view>
      </view>
    </view>
    
    <view class="pagination-section">
      <button class="pagination-button" :disabled="currentPage <= 1" @click="prevPage">上一页</button>
      <text class="page-info">第 {{ currentPage }} 页，共 {{ totalPages }} 页</text>
      <button class="pagination-button" :disabled="currentPage >= totalPages" @click="nextPage">下一页</button>
    </view>
    
    <view class="empty-state" v-if="coachList.length === 0">
      <text class="empty-text">暂无教练数据</text>
    </view>
    
    <!-- 创建/编辑教练弹窗 -->
    <view class="modal" v-if="showCoachModal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">{{ isEditCoach ? '编辑教练' : '添加教练' }}</text>
          <button class="close-button" @click="closeCoachModal">×</button>
        </view>
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">姓名</text>
            <input class="form-input" v-model="coachForm.name" placeholder="请输入教练姓名" />
          </view>
          <view class="form-item">
            <text class="form-label">手机号</text>
            <input class="form-input" v-model="coachForm.phone" placeholder="请输入手机号" />
          </view>
          <view class="form-item">
            <text class="form-label">邮箱</text>
            <input class="form-input" v-model="coachForm.email" placeholder="请输入邮箱" />
          </view>
          <view class="form-item">
            <text class="form-label">性别</text>
            <picker mode="selector" :range="genderOptions" @change="onGenderChange">
              <view class="form-input">{{ selectedGender || '请选择性别' }}</view>
            </picker>
          </view>
          <view class="form-item">
            <text class="form-label">专长</text>
            <input class="form-input" v-model="coachForm.specialty" placeholder="请输入专长" />
          </view>
          <view class="form-item">
            <text class="form-label">从业年限</text>
            <input class="form-input" type="number" v-model="coachForm.experience" placeholder="请输入从业年限" />
          </view>
          <view class="form-item">
            <text class="form-label">证书</text>
            <textarea class="form-textarea" v-model="coachForm.certificate" placeholder="请输入证书信息"></textarea>
          </view>
          <view class="form-item" v-if="isEditCoach">
            <text class="form-label">状态</text>
            <view class="status-toggle">
              <switch :checked="coachForm.status === 1" @change="onStatusChange" />
              <text class="status-text">{{ coachForm.status === 1 ? '在职' : '离职' }}</text>
            </view>
          </view>
        </view>
        <view class="modal-footer">
          <button class="action-button cancel" @click="closeCoachModal">取消</button>
          <button class="action-button" @click="saveCoach">保存</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { coachApi } from '../../src/services/coach'

// 定义教练类型
interface Coach {
  id: number
  name: string
  phone: string
  email: string
  gender: string
  specialty: string
  experience: number
  certificate: string
  status: number
  createdAt: string
  updatedAt: string
}

// 教练列表
const coachList = ref<Coach[]>([])

// 分页信息
const currentPage = ref(1)
const pageSize = ref(10)
const totalPages = ref(1)
const totalCoaches = ref(0)

// 是否显示教练弹窗
const showCoachModal = ref(false)

// 是否为编辑教练模式
const isEditCoach = ref(false)

// 当前编辑的教练
const currentCoach = ref<Coach>({ 
  id: 0, 
  name: '', 
  phone: '', 
  email: '', 
  gender: '', 
  specialty: '', 
  experience: 0, 
  certificate: '', 
  status: 1,
  createdAt: '',
  updatedAt: ''
})

// 教练表单
const coachForm = ref({
  name: '',
  phone: '',
  email: '',
  gender: '',
  specialty: '',
  experience: 0,
  certificate: '',
  status: 1
})

// 性别选项
const genderOptions = ['男', '女']
const selectedGender = ref('')

// 页面加载时获取教练列表
onMounted(() => {
  fetchCoachList()
})

// 获取教练列表
const fetchCoachList = async () => {
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    const response: any = await coachApi.getCoachList(params)
    coachList.value = response.data.list || response.data
    totalCoaches.value = response.data.total || coachList.value.length
    totalPages.value = Math.ceil(totalCoaches.value / pageSize.value)
    
    uni.showToast({
      title: '获取教练列表成功',
      icon: 'success'
    })
  } catch (error) {
    console.error('获取教练列表失败:', error)
    uni.showToast({
      title: '获取教练列表失败',
      icon: 'none'
    })
  }
}

// 显示创建教练弹窗
const showCreateCoachModal = () => {
  isEditCoach.value = false
  coachForm.value = { 
    name: '', 
    phone: '', 
    email: '', 
    gender: '', 
    specialty: '', 
    experience: 0, 
    certificate: '',
    status: 1
  }
  selectedGender.value = ''
  showCoachModal.value = true
}

// 编辑教练
const editCoach = (coach: Coach) => {
  isEditCoach.value = true
  currentCoach.value = { ...coach }
  coachForm.value = { ...coach }
  selectedGender.value = coach.gender
  showCoachModal.value = true
}

// 删除教练
const deleteCoach = async (coach: Coach) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除教练 "${coach.name}" 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          await coachApi.deleteCoach(coach.id)
          
          uni.showToast({
            title: '删除教练成功',
            icon: 'success'
          })
          
          // 重新获取教练列表
          fetchCoachList()
        } catch (error) {
          console.error('删除教练失败:', error)
          uni.showToast({
            title: '删除教练失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 跳转到教练详情页面
const goToDetail = (id: number) => {
  uni.navigateTo({
    url: `/pages/coach/detail?id=${id}`
  })
}

// 关闭教练弹窗
const closeCoachModal = () => {
  showCoachModal.value = false
}

// 性别选择变化
const onGenderChange = (e: any) => {
  selectedGender.value = genderOptions[e.detail.value]
  coachForm.value.gender = selectedGender.value
}

// 状态切换变化
const onStatusChange = (e: any) => {
  coachForm.value.status = e.detail.value ? 1 : 0
}

// 保存教练
const saveCoach = async () => {
  // 表单验证
  if (!coachForm.value.name) {
    uni.showToast({
      title: '请输入教练姓名',
      icon: 'none'
    })
    return
  }
  
  if (!coachForm.value.phone) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none'
    })
    return
  }
  
  try {
    if (isEditCoach.value && currentCoach.value.id) {
      // 编辑教练
      await coachApi.updateCoach(currentCoach.value.id, coachForm.value)
      
      uni.showToast({
        title: '更新教练成功',
        icon: 'success'
      })
    } else {
      // 创建教练
      await coachApi.createCoach(coachForm.value)
      
      uni.showToast({
        title: '创建教练成功',
        icon: 'success'
      })
    }
    
    // 关闭弹窗
    closeCoachModal()
    
    // 重新获取教练列表
    fetchCoachList()
  } catch (error) {
    console.error('保存教练失败:', error)
    uni.showToast({
      title: '保存教练失败',
      icon: 'none'
    })
  }
}

// 上一页
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    fetchCoachList()
  }
}

// 下一页
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    fetchCoachList()
  }
}
</script>

<style lang="scss" scoped>
.coach-list-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

.header-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  
  .page-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    text-align: center;
  }
}

.toolbar-section {
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  text-align: right;
}

.action-button {
  background-color: #4B0082;
  color: #fff;
  border: none;
  padding: 15rpx 30rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  
  &.small {
    padding: 10rpx 20rpx;
    font-size: 24rpx;
  }
  
  &.danger {
    background-color: #f44336;
  }
  
  &.cancel {
    background-color: #999;
  }
}

.coach-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.coach-item {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.coach-info {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
  margin-bottom: 20rpx;
}

.coach-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.coach-specialty {
  font-size: 28rpx;
  color: #4B0082;
}

.coach-contact {
  font-size: 24rpx;
  color: #666;
}

.coach-experience {
  font-size: 24rpx;
  color: #2196F3;
}

.coach-status {
  margin-bottom: 20rpx;
}

.status-tag {
  font-size: 24rpx;
  padding: 5rpx 15rpx;
  border-radius: 20rpx;
}

.status-active {
  background-color: #e8f5e9;
  color: #4caf50;
}

.status-inactive {
  background-color: #ffebee;
  color: #f44336;
}

.coach-actions {
  display: flex;
  gap: 10rpx;
  justify-content: flex-end;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 30rpx;
  padding: 0 20rpx;
}

.pagination-button {
  background-color: #4B0082;
  color: #fff;
  border: none;
  padding: 10rpx 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
}

.pagination-button[disabled] {
  background-color: #ccc;
}

.page-info {
  font-size: 28rpx;
  color: #666;
}

.empty-state {
  text-align: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  border-radius: 10rpx;
  width: 90%;
  max-width: 600rpx;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 2rpx solid #f5f5f5;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-button {
  background: none;
  border: none;
  font-size: 40rpx;
  color: #999;
  padding: 0;
  width: 50rpx;
  height: 50rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-body {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.form-item {
  margin-bottom: 30rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.form-input {
  background-color: #f5f5f5;
  padding: 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  width: 100%;
  box-sizing: border-box;
}

.form-textarea {
  background-color: #f5f5f5;
  padding: 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  width: 100%;
  height: 150rpx;
  box-sizing: border-box;
}

.status-toggle {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.status-text {
  font-size: 28rpx;
  color: #333;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 2rpx solid #f5f5f5;
}
</style>